package com.fbooks.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.fbooks.bean.Email;
import com.fbooks.bean.User;
import com.fbooks.mapper.UserMapper;
import com.fbooks.service.UserService;
import com.fbooks.utils.JWTutils;
import com.fbooks.utils.email.AccountEmailService;
import com.fbooks.utils.email.Impl.AccountEmailException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: LuoRunFeng
 * @e-mail: 475403147@qq.com
 * @Time: 2020/4/16 20:48
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Autowired
    private AccountEmailService accountEmailService;

    /**
     * 获取用户信息
     * @return
     */
    public List<User> getAllUser() {
        List<User> allUser = userMapper.getAllUser();
        return allUser;
    }


    /**
     * 用户登陆业务逻辑处理
     * @param email 邮箱
     * @param password 密码
     * @return
     */
    public JSONObject getUserInfo(String email,String password) {
        //存放响应信息
        JSONObject backInfo =new JSONObject();

        //根据用户账户获取用户信息
        //用户不存在 会异常
        try{
            User userInfo = userMapper.getUserInfo(email);
            // 注释掉token 放入生成新的token过长
            userInfo.setToken("");
            if (userInfo.getPassword().equals(password)){
                //账号密码都正确
                backInfo.put("info", "登陆成功！");
                backInfo.put("isSuccess", true);

                //生成token
                String token = JWTutils.sign(userInfo, 86400000*2);

                //同时将token存放到数据库
                userInfo.setToken(token);
                userMapper.updateToken(userInfo);
                //此时不再是默认token 里面包含最新token


                //返回信息不需要token password
                userInfo.setPassword("");
                backInfo.put("UserInfo", userInfo);

                return backInfo;
            }else{
                //密码不正确
                backInfo.put("info", "密码不正确！");
                backInfo.put("isSuccess", false);
                return backInfo;
            }
        }catch (Exception e){
            e.printStackTrace();
            backInfo.put("info", "账号不存在！");
            backInfo.put("isSuccess", false);
            return backInfo;
        }
    }


    /**
     * 用户注册
     * @param user
     * @return
     */
    public JSONObject saveUserInfo(User user) {

        //获取邮箱
        String email = user.getEmail();

        JSONObject registerInfo=new JSONObject();
        //首先需要判断账号是否已经存在了
        User userInfo = userMapper.getUserInfo(email);
        //判断userInfo是否存在
        if(userInfo==null){
            //email不存在
            //捕获异常
            try{
                //设置用户用户名
                String username = "fb_"+RandomStringUtils.random(7,"qwertyuioplkjhgfdsazxcvbnm1023456789");
                System.out.println(username);
                user.setUsername(username);
                userMapper.saveUserInfo(user);
                registerInfo.put("info", "注册成功");
                registerInfo.put("isSuccess", true);
                return registerInfo;
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            registerInfo.put("info", "邮箱已经被注册。请更换邮箱进行注册！");
            registerInfo.put("isSuccess", false);
            return registerInfo;
        }
        return registerInfo;
    }


    /**
     * 发送邮件
     * @param address
     * @throws AccountEmailException
     */
    public JSONObject sendEmail(String address) throws AccountEmailException {
        JSONObject backJson = new JSONObject();
        //生成验证码
        String str = "1234567890";
        String captchaCode = accountEmailService.createCaptchaCode(str,6);
        //这里设置主题啥的
        Email emailObject =new Email();
        emailObject.setAddressee(address);
        emailObject.setSubject("FBooks密码找回");
        emailObject.setContent("你的验证码为："+captchaCode);
        try{
            accountEmailService.sendMailByAsynchronousMode(emailObject);
            //返回成功标识  前端未响应数据且代表发送失败
            backJson.put("isSuccess", true);
            //验证码
            backJson.put("captchaCode", captchaCode);
            return backJson;
        }catch (Exception e){
            throw new AccountEmailException("UserService:邮件发送失败", e);
        }
    }

    /**
     * 通过token获取用户信息
     * @param token
     * @return
     */
    public JSONObject getUserInfo(String token) {
        JSONObject info = new JSONObject();
        //判断请求头token是否正确
        User user = JWTutils.unsign(token, User.class);
        //当token返回为空的时候
        //token错误的时候 返回也是null,过期也是null
        if(user != null){
            info.put("isSuccess",true);
            info.put("uid", user.getId());
            return info;
        }else {
            info.put("isSuccess",false);
            info.put("info","非法请求");
            return info;
        }
    }


    /**
     * 修改用户信息
     * @param user
     * @return
     */
    public JSONObject updateUserInfo(User user) {
        JSONObject jsonObject =new JSONObject();
        try{
            userMapper.updateUserInfo(user);
            //success
            jsonObject.put("isSuccess", true);
        }catch (Exception e){
            e.printStackTrace();
            //false
            jsonObject.put("isSuccess", false);
        }
        return jsonObject;
    }

    /**
     *  根据用户id删除用户信息
     * @param id
     * @return
     */
    public JSONObject deleteUserInfo(String id) {
        JSONObject jsonObject =new JSONObject();
        try{
            userMapper.deleteUserInfo(id);
            //success
            jsonObject.put("isSuccess", true);
        }catch (Exception e){
            e.printStackTrace();
            //false
            jsonObject.put("isSuccess", false);
        }
        return jsonObject;
    }


    /**
     *  根据用户id获取用户信息
     * @param id
     * @return
     */
    public User getUserInfoById(String id) {
        JSONObject jsonObject =new JSONObject();
        try{
            User userInfo = userMapper.getUserInfoById(id);
            //不返回token 将token置为空
            userInfo.setToken("");
            //success
            return userInfo;
        }catch (Exception e){
            e.printStackTrace();
            //false
        }
        return null;
    }

    /**
     * 修改头像
     * @param user
     */
    public void updateAvatar(User user) {
        userMapper.updateAvatar(user);
    }



    /**
     * 判断用户是否存在
     * @param email
     * @return
     */
    public boolean getUserInfoByEmail(String email) {
        User userInfo = userMapper.getUserInfo(email);
        System.out.println(userInfo);
        if (userInfo == null){
            return false;
        }else {
            return true;
        }
    }


    @Override
    public JSONObject updatePassword(User user) {
        JSONObject backInfo = new JSONObject();
        try{
            userMapper.updatePassword(user);
            backInfo.put("isSuccess", true);
            return backInfo;
        }catch (Exception e){
            e.printStackTrace();
            backInfo.put("isSuccess", false);
            return backInfo;
        }
    }

    @Override
    public User getUserInfoByToken(String token) {
        User user = userMapper.getUserInoByToken(token);
        return user;
    }

    public User selectUserInfoById(String id) {
        User user = userMapper.selectUserInfoById(id);
        return user;
    }

    @Override
    public void deleteUser(String id) {
        userMapper.deleteUserInfo(id);
    }
}
